#--------------
# measure opioid - therapy transition : 
#==============
load_library = c('bit64','data.table','fst','future.apply','stringr','logger','vroom')
invisible(lapply(load_library, function(x) library(x, character.only=TRUE, quietly= TRUE)))

bucket = '/N/project/iuni_doctorshopping'

args=commandArgs(TRUE)
infile_opioid = args[[1]]
infile_therapy = args[[2]]
outfile = args[[3]]

year = stringr::str_extract(basename(infile_opioid),'\\d{4}') %>% as.integer
week = stringr::str_extract(basename(infile_opioid),'W\\d{2}') %>% gsub('W','',.)  %>% as.integer
yw = stringr::str_extract(basename(infile_opioid),'\\d{4}W\\d{2}') 

future_week = week + 1 
if (future_week > 52) {
	future_week = 1 
	future_year = year + 1 

} else {
	future_year = year 
}

	future_yw = paste0(year,'W',stringr::str_pad(future_week,pad='0', width=2))
	future_infile_opioid = gsub(yw, future_yw, infile_opioid)
	future_infile_therapy = gsub(yw, future_yw, infile_therapy)

dt_opioid = fread(infile_opioid)
dt_opioid[,opioid_t0 := 1]

dt_therapy = fread(infile_therapy)
dt_therapy  = dt_therapy[, .N, by='PATID']
dt_therapy[, N := NULL]
dt_therapy[,therapy_t0 := 1]

dt = merge(dt_opioid, dt_therapy, by='PATID', all=TRUE)
dt[is.na(opioid_t0), opioid_t0 := 0]
dt[is.na(therapy_t0), therapy_t0 := 0]

# also add future file
if (!file.exists(future_infile_opioid)) {
	dt[, opioid_t1 := 0]
	dt[, therapy_t1 := 0]
} else {
	dt_therapy_t1 = fread(future_infile_therapy)
	dt_therapy_t1  = dt_therapy_t1[, .N, by='PATID']
	dt_therapy_t1[, N := NULL]
	dt_therapy_t1[,therapy_t1 := 1]
	
	dt_opioid_t1 = fread(future_infile_opioid)
	dt_opioid_t1[,opioid_t1 := 1]

	dt = merge(dt, dt_therapy_t1, by='PATID', all.x=TRUE)
	dt = merge(dt, dt_opioid_t1, by='PATID', all.x=TRUE)

	dt[is.na(opioid_t1), opioid_t1 := 0]
	dt[is.na(therapy_t1), therapy_t1 := 0]
}

fwrite(dt, outfile)
